package ModelLayer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
/**
 * Write a description of class FileDiscount here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class FileDiscount
{
    private File file;
    private BufferedWriter bw;
    private FileWriter fw;
    private FileReader fr;
    private BufferedReader br;
    private double[] old_discounts;

    /**
     * Constructor for objects of class FileDiscount
     */
    public FileDiscount()
    {
       file = new File("Discount.txt");
       if(!(file.exists()))
       {
           try
           {
               file.createNewFile();
           }
           
           catch (IOException e)
           {
           }
       }
       old_discounts = get_discounts();
    }
    
    public void save_discounts(double[] new_discounts)
    {
        if(!(old_discounts.equals( new_discounts)))
        {
            try
            {
                fw = new FileWriter(file);
                bw = new BufferedWriter(fw);
                bw.write("" + new_discounts[0] + "\t" + new_discounts[1]);
                bw.close();
                old_discounts = get_discounts();
            }
            catch (IOException e)
            {
                System.out.println("HA, just crashed on IOException");
            }
        }
    }
    
    public double[] get_discounts()
    {
        double[] data = new double[2];
        String line = "";
         try
        {
            fr = new FileReader(file);
            try
            {
                br = new BufferedReader(fr);
                line = br.readLine();
                br.close();
            }
            catch (IOException e)
            {
            }
        }
        catch (FileNotFoundException ex)
        {
        }
        
        if(line == null || line.equals(""))
        {
            data[0] = 0;
            data[1] = 0;
        }
        else
        {
            String[] strs = line.split("\t");
            if(!(strs[0].equals("")))
            {
                data[0] = Double.parseDouble(strs[0]);
            }
            else
            {
                data[0] = 0;
            }
            if(strs.length != 1)
            {
                if(!(strs[1].equals("")))
                {
                    data[1] = Double.parseDouble(strs[1]);
                }
                else
                {
                    data[1] = 0;
                }
            }
            else
            {
                data[1] = 0;
            }
        }
        return data;
    }


}
